package logic

import (
	"MyBlogs/dao/mysql"
	"MyBlogs/models"
	"fmt"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

type Article struct {
	Title     string `form:"title"`
	Type      string `form:"type"`
	Introduce string `form:"introduce"`
	Content   string `form:"content"`
}

// 所有文章
func GetArticles(context *gin.Context) {
	art := mysql.GetArticles()
	context.JSON(200, gin.H{
		"art": art,
	})
}

// 某一个文章
func GetArticle(context *gin.Context) {
	var id int64
	idStr := context.Query("id")
	id, _ = strconv.ParseInt(idStr, 10, 64)
	art := mysql.GetArticle(id)
	context.JSON(200, gin.H{
		"art": art,
	})
}

// 添加文章
func AddArticle(context *gin.Context) {
	var art *models.Article
	err := context.ShouldBind(&art)
	if err != nil {
		fmt.Printf(err.Error())
	}
	art.CreateTime = time.Now().Format("2006-01-02 15:04:05")
	art.UpdateTime = time.Now().Format("2006-01-02 15:04:05")
	mysql.AddArticle(art)
}

// 删除文章
func DelArticle(context *gin.Context) {
	idStr, _ := context.GetPostForm("id")
	id, _ := strconv.ParseInt(idStr, 10, 64)
	mysql.DelArticle(id)
}

// 修改文章
func ModArticle(context *gin.Context) {
	var art *models.Article
	err := context.ShouldBind(&art)
	if err != nil {
		fmt.Printf(err.Error())
	}
	idStr, _ := context.GetPostForm("id")
	id, _ := strconv.ParseInt(idStr, 10, 64)
	art.UpdateTime = time.Now().Format("2006-01-02 15:04:05")
	mysql.ModArticle(id, art)
}

// 查新文章
func FindArticle(context *gin.Context) {
	cont, _ := context.GetPostForm("title")
	art := mysql.FindArticle(cont)
	context.JSON(200, gin.H{
		"art": art,
	})
}
